import {history, post, message, get, ocr as ocrApi} from '@/utils/utils'
import {versionNum} from '@/config'
import dayjs from 'dayjs'

const filesKeys = {
  1: 'personFront',
  2: 'personCard',
  3: 'idCardFront',
  4: 'idCardBack',
  5: 'bankCard'
}

const auth = {
  namespaced: true,
  state: {
    files: {
      personFront: '',
      personCard: '',
      idCardFront: '',
      idCardBack: '',
      bankCard: ''
    },

    authInfo: {
      name: '',
      gender: '2',
      idCardNo: '',

      bankCardNo: '',
      bankCardBelong: ''
    },
    showAuth: false
  },

  mutations: {
    save(state, {field, payload}) {
      if (Object.prototype.toString.call(payload) === '[object Object]') {
        state[field] = { ...state[field], ...payload }
      } else {
        state[field] = payload
      }
    }
  },

  actions: {
    save({ commit }, payload) {
      commit('save', payload)
    },

    filesChange({ commit }, payload) {
      commit('save', { field: 'files', payload })
    },

    authInfoChange({ commit }, {$wx, target}) {
      const key = target.dataset.key
      const value = typeof $wx.detail === 'object' ? $wx.detail.value : $wx.detail
      commit('save', { field: 'authInfo', payload: {[key]: value} })
    },

    submit({ commit, state, dispatch, rootState }) {
      const {authInfo, files} = state
      const {name, gender, idCardNo, bankCardNo, bankCardBelong, idCardStartDate, idCardEndDate} = authInfo

      const getUploadValue = (value) => value.includes('*') ? undefined : value

      const agentCertification = {
        agentBankcard: {
          agentIdNo: getUploadValue(idCardNo),
          agentName: getUploadValue(name),
          agentBankName: getUploadValue(bankCardBelong),
          agentBankcardNo: getUploadValue(bankCardNo),
          idNoStart: getUploadValue(idCardStartDate),
          idNoEnd: getUploadValue(idCardEndDate)
        },
        files: [
          {
            fileType: '15',
            fileUrl: files.personFront.fileUrl
          },
          {
            fileType: '16',
            fileUrl: files.personCard.fileUrl
          },
          {
            fileType: '02',
            fileUrl: files.idCardFront.fileUrl
          },
          {
            fileType: '03',
            fileUrl: files.idCardBack.fileUrl
          },
          {
            fileType: '05',
            fileUrl: files.bankCard.fileUrl
          }
        ]
      }

      post({
        api: '/agt/agentinfo/certification',
        data: agentCertification,
        success: ({data}) => {
          message.success({msg: '提交成功',
            onClose: () => {
              history.push('/pages/auth/authResult?fromAuth=true')
            }})

          commit('home/save', {field: 'agentInfo', payload: {agentStatus: '2'}}, {root: true})
        }
      })
    },

    getAuthInfo({ commit }, agentInfo) {
      const { agentName, gender, agentIdNo, agentBankcardNo, agentBankName, idNoStart, idNoEnd, idNoAddress } = agentInfo
      const authInfo = {
        name: agentName,
        gender,
        idCardNo: agentIdNo,
        idCardStartDate: idNoStart,
        idCardEndDate: idNoEnd,
        bankCardNo: agentBankcardNo,
        idNoAddress,
        bankCardBelong: agentBankName
      }

      commit('save', {field: 'authInfo', payload: authInfo})

      post({
        api: '/agt/agentfile/getFileList',
        success: ({data}) => {
          console.log(data)

          data.forEach((pic) => {
            pic.url = pic.fileUrl
            pic.thumb = pic.fileUrl
          })

          const [personFront, personCard, idCardFront, idCardBack, bankCard] = data

          const files = {
            personFront,
            personCard,
            idCardFront,
            idCardBack,
            bankCard
          }

          commit('save', {field: 'files', payload: files})
        }
      })
    },

    detectShowAuth({ commit }) {
      get({
        api: `/agt/auditSwitch/${versionNum}`,
        noLoading: true,
        noTip: true,
        success: ({data}) => {
          commit('save', {field: 'showAuth', payload: data === '0'})
        }
      })
    },

    ocr({ commit, dispatch }, {file, key}) {
      ocrApi(file.fileUrl, key === '5' ? 2 : 1)
      .then(({data}) => {
        const {idcard_res = {}, bankcard_res = {}} = data

        if (key === '3') {
          const {name: {text: name}, gender: {text: gender}, id: {text: idCardNo}, address: {text: idNoAddress}} = idcard_res

          commit('save', {field: 'authInfo', payload: {name, idCardNo, idNoAddress, gender: gender === '男' ? '2' : '1'}})
        } else if (key === '4') {
          const {valid_date: {text: date}} = idcard_res
          const [startDate, endDate] = date && date.split('-')

          const idCardStartDate = dayjs(startDate).format('YYYY-MM-DD')
          const idCardEndDate = dayjs(endDate).format('YYYY-MM-DD')

          commit('save', {field: 'authInfo', payload: {idCardStartDate, idCardEndDate}})
        } else if (key === '5') {
          const {number: {text: bankCardNo}} = bankcard_res

          commit('save', {field: 'authInfo', payload: {bankCardNo}})
          dispatch('identifyBankcard', bankCardNo)
        }
      })
    },

    identifyBankcard({ commit }, cardNo) {
      get({
        api: `/mec/bankcardbinuseful/queryBankCardBinByCardNo/${cardNo}`,
        success: ({data}) => {
          commit('save', {field: 'authInfo', payload: {bankCardBelong: data.bnkBnm}})
        }
      })
    },

    getEidToken({state: {authInfo: {name, idCardNo}}}) {
      return get({
        api: '/agt/faceCompare/getEidToken'
      })
    }
  }
}

export default auth

export {
  filesKeys
}
